package com.tuniu.agents.impl.train;

import com.tuniu.agents.agent.AgentManagerGroup;
import com.tuniu.agents.common.agent.Recommender;
import com.tuniu.agents.common.handler.IStreamResponseHandler;
import com.tuniu.agents.common.i18n.I18nConstants;
import com.tuniu.agents.common.message.BaseAgentNewResp;
import com.tuniu.agents.util.I18nUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.UserMessage;
import reactor.core.publisher.Flux;

import java.util.List;
import java.util.Map;

import static com.tuniu.agents.tools.train.tool.SearchAllTrainTool.convertJsonToMark;

/**
 * base train ticket recommender agent
 */
public class TrainRecommender extends Recommender {

    private static final Logger logger = LoggerFactory.getLogger(TrainRecommender.class);

    public TrainRecommender(AgentManagerGroup agentManagerGroup, String agentId, String promptTemplateId, IStreamResponseHandler streamResponseHandler) {
        super(agentManagerGroup, agentId, promptTemplateId, streamResponseHandler,false,false);
    }

    public TrainRecommender(AgentManagerGroup agentManagerGroup, String agentId, String promptTemplateId) {
        super(agentManagerGroup, agentId, promptTemplateId);
    }

    @Override
    public Flux<String> stream(String conversationId, List<Message> messages, Map<String, Object> context) {
        String message = messages.get(0).getText();
        if(StringUtils.isBlank(message) || "null".equals(message)){
            logger.error("TrainRecommender train stream agent error message is null");
            return Flux.just(BaseAgentNewResp.sendErrorMsg(I18nUtil.getMessage(I18nConstants.COMMON_SYSTEM_ERROR_MESSAGE_KEY), null));
        }
        //convert json to markdown
        String markdownMsg = convertJsonToMark(message,conversationId);
        Flux<String> flux = this.chatClientRequestSpec(conversationId, List.of(new UserMessage(markdownMsg)), context).stream().content();
        Map<String, Object> params = Map.of("message", message,"conversationId",conversationId);
        return streamResponseHandler == null ? flux : streamResponseHandler.handle(params,flux);
    }
}
